/**
 * User: Paulo Fournier
 * Date: 12-08-2013
 * Poi app controller
 */

Ext.define('Mobile-app.controller.Poi', {
    extend: 'Ext.app.Controller',

    config: {
        //add view references for this controller
        refs: {
            poiPanel: 'poipanel',
            poiDetailPanel: 'poidetailpanel',
            editPoiPanel: 'editpoipanel',
            mobileDetailPanel: 'mobiledetailpanel',
            addPoiPanel: 'addpoipanel',
            mapPanel: 'mappanel'
        },

        //Definition of all listen events of this controller
        //can be triggered by the [fireEvent] method
        control: {

            poiPanel: {
                showDetails: 'onShowDetails',
                loadStore: 'onLoadStore'
            },

            poiDetailPanel: {
                showMarker: 'onShowMarker',
                showEditPanel: 'onShowEditPanel',
                showDeleteMessage: 'onShowDeleteMessage'
            },

            mobileDetailPanel: {
                showAddPoiPanel: 'onShowAddPoiPanel'
            },

            addPoiPanel: {
                saveNewPoi: 'onSaveNewPoi'
            },

            editPoiPanel: {
                saveEditPoi: 'onSaveEditPoi'
            },

            mapPanel: {
                showAddPoiPanel: 'onShowAddPoiPanel'
            }

        }

    },

    /***
     * Used to show the details of a mobile
     * @param list Ext.DataView.List
     * @param record The record associated to the item
     */
    onShowDetails: function (list, record) {

        //save record information
        this.selectdRecord = record;

        if (!this.getPoiDetailPanel()) {

            //load MobileDetail view with this record information
            var view = Ext.create('Mobile-app.view.PoiDetail');

            //add view to body viewport
            Ext.Viewport.add(view);

        }
        else
            view = this.getPoiDetailPanel();

        //show window
        view.show();

        //set record to all view panels
        view.items.first().items.each(function (p) {
            p.setRecord(record)
        });

        //get map object
        var map = view.down('map').getMap();

        //if map no found, do nothing!
        if (!map) return;

        //set position
        var latLong = new google.maps.LatLng(record.get('latitude'), record.get('longitude'));

        //only update map if the record was found
        if (!map.marker)
            map.marker = new google.maps.Marker({
                position: latLong,
                map: map
            });
        else
            map.marker.setPosition(latLong);

        //center map
        map.setCenter(latLong);

    },

    /***
     * Will show the vehicle marker on the map and center it
     * @param mapPanel The map object Ext.Map
     */
    onShowMarker: function (mapPanel) {

        //set position
        var record = this.selectdRecord,
            map = mapPanel.getMap(),
            latLong = new google.maps.LatLng(record.get('latitude'), record.get('longitude'));

        //check if marker exists, if so, only update the position
        if (!map.marker)
            map.marker = new google.maps.Marker({
                position: latLong,
                map: map
            });
        else
            map.marker.setPosition(latLong);

        //center map
        map.setCenter(latLong);

    },

    /***
     * Will load the list store
     * @param listPanel The lest panel to reload the data
     */
    onLoadStore: function (listPanel) {
        listPanel.getStore().load();
    },

    /**
     * Will show the panel (Edit POI) Panel
     * @param poiRecord The target POI that will be edit
     */
    onShowEditPanel: function (poiRecord) {

        this.selectedPoiRecord = poiRecord;

        //hide detail window
        this.getPoiDetailPanel().hide();

        if (!this.getEditPoiPanel()) {
            //load AddPoi view with this record information
            var view = Ext.create('Mobile-app.view.EditPoi');

            //add view to body viewport
            Ext.Viewport.add(view);

        }
        else {
            this.getEditPoiPanel().show();
        }

        //set form record
        this.getEditPoiPanel().setRecord(poiRecord);
    },

    /***
     * Will show the panel (Add POI) Panel
     * @param mobileRecord The selected record to retrieve thr lat/lng values
     */
    onShowAddPoiPanel: function (mobileRecord) {

        //save record information
        this.selectedRecord = mobileRecord;

        if (!this.getAddPoiPanel()) {
            //load AddPoi view with this record information
            var view = Ext.create('Mobile-app.view.AddPoi');

            //add view to body viewport
            Ext.Viewport.add(view);

        }
        else {
            this.getAddPoiPanel().show();
        }
    },

    /***
     * Controller to validate and submit the add new poi form
     * @param fields The form fields
     */
    onSaveNewPoi: function (fields) {

        // validar o resto dos camposs
        if (!fields.get('name').getValue()) {
            Ext.Msg.alert($.t('general.error'), $.t('error.7',{name: $.t('main.name')}), Ext.emptyFn);
        }
        else if (!fields.get('description').getValue()) {
            Ext.Msg.alert($.t('general.error'), $.t('error.7',{name: $.t('main.description')}), Ext.emptyFn);
        }
        else if(fields.get('maximumTimeOfPermanence').getValue() === null || !fields.get('maximumTimeOfPermanence').getValue() < 0){
            Ext.Msg.alert($.t('general.error'), $.t('error.9',{name: $.t('main.maximum permanence time')}), Ext.emptyFn);
        }
        else if (fields.get('radius').getValue() <= 0) {
            Ext.Msg.alert($.t('general.error'), $.t('error.8',{name: $.t('main.radius')}), Ext.emptyFn);
        }
        else {

            /// ext.save()
            var newPoi = Ext.create('Mobile-app.model.Poi', {
                name: fields.get('name').getValue(),
                description: fields.get('description').getValue(),
                category: fields.get('category').getValue(),
                latitude: this.selectedRecord.get('latitude'),
                longitude: this.selectedRecord.get('longitude'),
                radius: fields.get('radius').getValue(),
                maximumTimeOfPermanence: fields.get('maximumTimeOfPermanence').getValue()
            });

            //show loading mask
            this.getAddPoiPanel().setMasked({
                xtype: 'loadmask',
                message: $.t('main.loading').toLowerCase() + '...'
            });

            //submit form
            newPoi.save({
                success: function (record, options) {

                    this.getAddPoiPanel().setMasked(false);

                    var rst = Ext.JSON.decode(options.getResponse().responseText);

                    record.set('id', rst.newId);

                    var list = this.getPoiPanel().down('list');
                    list.getStore().add(record);

                    Ext.Msg.alert($.t('main.add poi'), $.t('main.add poi successfully'), Ext.emptyFn);
                    //debugger;
                    this.getAddPoiPanel().reset();
                    this.getAddPoiPanel().hide();

                },
                failure: function () {
                    Ext.Msg.alert($.t('general.error'), $.t('error.11'), Ext.emptyFn);
                    this.getAddpoipanel().setMasked(false);
                }
            }, this);

        }

    },

    /***
     * Controller to validate and submit the edit poi form
     * @param fields The form fields
     */
    onSaveEditPoi: function (fields) {

        if (!fields.get('name').getValue()) {
            Ext.Msg.alert($.t('general.error'), $.t('error.7',{name: $.t('main.name')}), Ext.emptyFn);
        }
        else if (!fields.get('description').getValue()) {
            Ext.Msg.alert($.t('general.error'), $.t('error.7',{name: $.t('main.description')}), Ext.emptyFn);
        }
        else if(fields.get('maximumTimeOfPermanence').getValue() === null || !fields.get('maximumTimeOfPermanence').getValue() < 0){
            Ext.Msg.alert($.t('general.error'), $.t('error.9',{name: $.t('main.maximum permanence time')}), Ext.emptyFn);
        }
        else if (fields.get('radius').getValue() <= 0) {
            Ext.Msg.alert($.t('general.error'), $.t('error.8',{name: $.t('main.radius')}), Ext.emptyFn);
        }
        else {

            var record = this.getEditPoiPanel().getRecord();

            //update record
            fields.each(function(field){
                //update value
                record.set(field.getName(), field.getValue());

            },this);

            //also save category name on record
            record.set('category', fields.get('idCategory').record.data.description);

            //show loading mask
            this.getEditPoiPanel().setMasked({
                xtype: 'loadmask',
                message: $.t('main.loading').toLowerCase() + '...'
            });

            record.save({
                success: function (record, options) {

                    Ext.Msg.alert($.t('main.edit poi'), $.t('main.edit poi successfully'), Ext.emptyFn);

                    //reset form and hide it
                    this.getEditPoiPanel().reset();
                    this.getEditPoiPanel().hide();

                    this.getEditPoiPanel().setMasked(false);
                },
                failure: function () {
                    Ext.Msg.alert($.t('general.error'), $.t('error.10'), Ext.emptyFn);

                    this.getEditPoiPanel().setMasked(false);
                }
            }, this);


        }
    },

    /***
     * Will delete the POI record
     * @param poiRecord
     */
    onShowDeleteMessage: function (poiRecord) {

        //show loading mask
        this.getPoiDetailPanel().setMasked({
            xtype: 'loadmask',
            message: $.t('main.loading').toLowerCase() + '...'
        });

        //erase POI
        poiRecord.erase({
            success: function (record, options) {

                Ext.Msg.alert($.t('main.remove poi'), $.t('main.remove poi successfully'), Ext.emptyFn);
                this.getPoiDetailPanel().hide();

                this.getPoiDetailPanel().setMasked(false);
            },
            failure: function () {
                Ext.Msg.alert($.t('general.error'), $.t('error.12'), Ext.emptyFn);

                this.getPoiDetailPanel().setMasked(false);
            }
        }, this);
    }

});